package org.dromara.web.CssUtil;

import com.alibaba.fastjson.JSON;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.enums.WxApiType;
import com.ijpay.wxpay.enums.WxDomain;
import com.ijpay.wxpay.model.RefundModel;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.dromara.app.appParams.AppPayParams;
import org.dromara.app.domain.SkMembershipOrder;
import org.dromara.app.domain.SkYueDanOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @auther Cai Shuai Shuai
 * @data 2025/2/20
 * @apiNode
 */
@RequiredArgsConstructor
@Service
public class CssOrderPaySever {

    @Autowired
    WxPayBean wxPayBean;

    private final static String NOTIFY_URL = "/ZjReadingClub/api/notify_url";

    /**
     * 预约订单微信APP支付
     */
    public String appYyPay(HttpServletRequest request, SkYueDanOrder order) {
        AppPayParams app = new AppPayParams();
        app.setOutTradeNo("YY-"+order.getId());
        app.setTotalFee(order.getPayPrice().multiply(new BigDecimal(100)).intValue()+"");
        app.setBody("预约订单");
        app.setType("2");
        System.out.println("预约订单微信APP支付: "+JSON.toJSONString(app));
        return wxAppPay(request,app);
    }
    /**
     * 会员订单微信APP支付
     */
    public String appVipPay(HttpServletRequest request, SkMembershipOrder order) {
        AppPayParams app = new AppPayParams();
        app.setOutTradeNo("VIP-"+order.getId());
        app.setTotalFee(order.getPrice().multiply(new BigDecimal(100)).intValue()+"");
        app.setBody("开通会员");
        app.setType("1");
        return wxAppPay(request,app);
    }
    /**
     * 微信支付
     * @Author CaiShuaiShuai
     * @Date   14:23 2022/7/20
     * @Param  * @param null
     * @return
     **/
    public String wxAppPay(HttpServletRequest request, AppPayParams order) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null) {
            // 如果X-Forwarded-For不存在，尝试使用RemoteAddr
            ipAddress = request.getRemoteAddr();
        } else {
            // 可能会有多个IP地址，例如通过逗号分隔，取第一个逗号前的IP
            int commaIndex = ipAddress.indexOf(',');
            if (commaIndex != -1) {
                ipAddress = ipAddress.substring(0, commaIndex);
            }
        }
        if (ipAddress.isEmpty()){
            ipAddress = "127.0.0.1";
        }
        String notifyUrl = "";
        if (order.getType().equals("1"))    {
            notifyUrl = wxPayBean.getDomain()+wxPayBean.getCznotifyUrl();
        }   else {
            notifyUrl = wxPayBean.getDomain()+wxPayBean.getNotifyUrl();
        }
        Map<String, String> params = UnifiedOrderModel
            .builder()
            .appid(wxPayBean.getAppId())
            .mch_id(wxPayBean.getMchId())
            .nonce_str(WxPayKit.generateStr())
            .body(order.getBody())
            .attach(order.getBody())
            .out_trade_no(order.getOutTradeNo())
            .total_fee(order.getTotalFee())
            .spbill_create_ip(ipAddress)
            .notify_url(notifyUrl)
            .trade_type(TradeType.APP.getTradeType())
            .build()
            .createSign(wxPayBean.getPartnerKey(), SignType.HMACSHA256);

        String xmlResult = WxPayApi.pushOrder(false, params);

        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            return returnMsg;
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            return returnMsg;
        }
        // 以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回
        String prepayId = result.get("prepay_id");
        Map<String, String> packageParams = WxPayKit.appPrepayIdCreateSign(wxPayBean.getAppId(), wxPayBean.getMchId(), prepayId,
            wxPayBean.getPartnerKey(), SignType.HMACSHA256);
        String jsonStr = JSON.toJSONString(packageParams);
        System.out.println("预约订单微信APP支付jsonStr: "+jsonStr);
        return jsonStr;
    }

    /**
     * 支付成功回调
     */
    public Map<String, String> callback(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine())!= null) {
            sb.append(line);
        }
        String xmlData = sb.toString();
        // 将XML数据解析为Map
        Map<String, String> data = WxPayKit.xmlToMap(xmlData);

        return data;
    }

    public String refund(SkYueDanOrder skYueDanOrder) {
        String refundNotifyUrl = wxPayBean.getDomain() + wxPayBean.getRefundNotifyUrl();
        Map<String, String> params = RefundModel.builder()
            .appid(wxPayBean.getAppId())
            .mch_id(wxPayBean.getMchId())
            .nonce_str(WxPayKit.generateStr())
            .transaction_id(skYueDanOrder.getPayOrder())
            .out_trade_no("YY-"+skYueDanOrder.getId())
            .out_refund_no("TK-"+skYueDanOrder.getId())
            .total_fee(skYueDanOrder.getPayPrice().multiply(new BigDecimal(100)).intValue()+"")
            .refund_fee(skYueDanOrder.getRefundPrice().multiply(new BigDecimal(100)).intValue()+"")
            .notify_url(refundNotifyUrl)
            .build()
            .createSign(wxPayBean.getPartnerKey(), SignType.MD5);
        System.out.println("params:"+params);
        String refundStr = HttpKit.getDelegate().post(WxPayApi.getReqUrl(WxApiType.REFUND, (WxDomain) null, false), WxPayKit.toXml(params), wxPayBean.getCertPath(), wxPayBean.getMchId(), "");
        System.out.println("refundStr:"+refundStr);
        return refundStr;
    }

    public static void main(String[] args) {
        String refundNotifyUrl = "/xxxx";
        Map<String, String> params = RefundModel.builder()
            .appid("wxf8fdce486f591c4f")
            .mch_id("1684729164")
            .nonce_str(WxPayKit.generateStr())
            .transaction_id("4200002625202503052671423610")
            .out_trade_no("YY-1897144397325213697")
            .out_refund_no("RE-1897144397325213697")
            .total_fee("0.7")
            .refund_fee("0.7")
            .notify_url(refundNotifyUrl)
            .build()
            .createSign("shangkehuajie1212345012345678912", SignType.MD5);
        System.out.println(params);
        String refundStr = WxPayApi.orderRefund(false, params, "D:/CSSXM2.0/尚客花街/1684729164_20250306_cert/apiclient_cert.pem","1684729164");
        System.out.println(refundStr);
    }
}
